var s = require("../../mainInfo.js");
var n = require("../../tipInfo.js");

Page({
  data: {
    SHOW_TOP: true,
    images: {
      magnifier: "/images/tab_bar_icon_magnifier.png",
      qrB: "/images/qr_b.png",
      wsgQr: "/images/zsm.jpg",
      location: "/images/location.png",
      broadcast: "/images/broadcast.png"
    },
    tipInfo: n.tipInfo,
    city: "shanghai",
  },
  pickImage: function () {
    var that = this;
    wx.showLoading({
      title: '识别中',
    });
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=jWxAYgY9TaEmsCqyrvkwYzZw&client_secret=mn9tOlL0DeEb6XCMZLoFhIHQPohwzTuX',
      success: res => {
        var token = res.data.access_token;
        wx.chooseImage({
          count: 1,
          success: (chooseres) => {
            console.log(chooseres);
            wx.cloud.uploadFile({
              cloudPath: "img/" + new Date().getTime() + "-" + Math.floor(Math.random() * 1000),
              filePath: chooseres.tempFilePaths[0],
              success: (uploadres) => {
                console.log(uploadres);
                wx.cloud.getTempFileURL({
                  fileList: [uploadres.fileID],
                  success: res => {
                    wx.request({
                      url: res.fileList[0].tempFileURL,
                      responseType: 'arraybuffer',
                      success: res => {
                        let base64 = wx.arrayBufferToBase64(res.data);
                        wx.request({
                          url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general',
                          method: "POST",
                          data: {
                            "access_token": token,
                            "image": encodeURI(base64)
                          },
                          header: {
                            "Content-Type": "application/x-www-form-urlencoded"
                          },
                          success: res => {
                            wx.hideLoading({
                              success: (res) => { },
                            });
                            if (res.data.result.length > 0) {
                              wx.showToast({
                                title: '识别成功',
                              });
                              wx.navigateTo({
                                url: './search?text=' + res.data.result[0].keyword,
                              });
                              that.setData({
                                searchtxt: res.data.result[0].keyword
                              });
                            } else {
                              wx.showToast({
                                title: '识别失败',
                              });
                            }
                          }
                        });
                      },
                      fail: console.error
                    });
                  },
                  fail: console.error
                });
              },
              fail: (err) => {
                console.log(err);
              }
            });
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    });
  },
  onLoad: function (options) {
    this.initData();
    wx.showShareMenu({
      withShareTicket: true
    });

    var myDate = new Date();
    var isShowed = wx.getStorageSync("tip");
    if (isShowed!= 1) {
      setTimeout(() => {
        this.setData({
          SHOW_TOP: false
        });
        wx.setStorageSync("tip", 1);
      }, 2 * 1000);
    } else {
      this.setData({
        SHOW_TOP: false
      });
    }
  },

  initData: function () {
    if (wx.getStorageSync("city") === undefined || wx.getStorageSync("city").length === 0) {
      wx.setStorageSync("city", this.data.city);
    } else {
      this.setData({
        city: wx.getStorageSync("city")
      });
    }
    var e = [];
    for (var a in s.default.cities) {
      e.push(s.default.cities[a]);
    }
    this.setData({
      tipInfo: n.tipInfo,
      config: s.default,
      cities: e
    });
  },
  onShow: function () {
    this.setData({
      tipInfo: n.tipInfo
    });
    wx.getStorageSync("city")!== this.data.city && this.setData({
      city: wx.getStorageSync("city"),
    });
    this.setFakeSearchLeft();
  },
  startSearch: function (t) {
    wx.navigateTo({
      url: "../ai/search"
    });
  },
  chooseCity: function (t) {
    var e = t.currentTarget.dataset.itemKey;
    if (e!== this.data.city) {
      wx.setStorageSync("city", e);
      this.setData({
        city: e,
        showChooseCity: false,
        enableScroll: true
      });
      this.setFakeSearchLeft();
    }
  },
  closeOverlay: function () {
    this.setData({
      showChooseCity: false,
      enableScroll: true
    });
  },
  showChooseCity: function () {
    this.setData({
      showChooseCity: true,
      enableScroll: false
    });
  },
  switchToTest: function () {
    wx.switchTab({
      url: "/pages/test/test"
    });
  },
  setFakeSearchLeft: function () {
    var t = this;
    wx.createSelectorQuery().select("#currentCity").boundingClientRect(function (e) {
      t.setData({
        fakeSearchLeft: "left: calc(25rpx + 21rpx + " + e.width + "px);"
      });
    }).exec();
  },
  goSearch: function () {
    wx.navigateTo({
      url: 'search',
    });
  },
  onBindCamera: function () {
    wx.getSetting({
      success(res) {
        console.log(res);
        if (!res.authSetting['scope.camera']) {
          wx.authorize({
            scope: 'scope.camera',
            success() {
              wx.navigateTo({
                url: 'camera/camera',
              });
            }
          });
        } else {
          wx.navigateTo({
            url: 'camera/camera',
          });
        }
      }
    });
  },
  onAikefu: function () {
    wx.navigateTo({
      url: '/pages/android/qa',
    });
  },
  onShareAppMessage: function () {
    return {
      title: "智能分类垃圾",
      imageUrl: "../../images/no-result.png",
      path: "pages/ai/index"
    };
  },
  showZsm: function (t) {
    wx.previewImage({
      current: "https://6465-dev-oto5o-1257020492.tcb.qcloud.la/zsm.jpg?sign=630ef20ce52101ba29f99c6bc1934835&t=1576025106",
      urls: ["https://6465-dev-oto5o-1257020492.tcb.qcloud.la/zsm.jpg?sign=630ef20ce52101ba29f99c6bc1934835&t=1576025106"],
    });
  }
})